import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Objects;

/**
 * @author sk.z
 */

public class UpdateDns {

    private static final String baseUrl = "https://ipv4.dynv6.com/api/update?ipv4=auto&zone={0}&token={1}";

    public static void send(String zone, String token){
        String url = MessageFormat.format(baseUrl,zone, token);

        String s = httpGet(url);
        System.out.println(s);
    }

    private static String httpGet(String urlStr) {
        BufferedReader reader = null;
        StringBuilder sb = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(6000);

            int responseCode = urlConnection.getResponseCode();
            if (responseCode != 200) {
                System.out.println("connect [" + urlStr + "] : " + responseCode + " " + urlConnection.getResponseMessage());
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            sb = new StringBuilder();
            String read;
            while ((read = reader.readLine()) != null) {
                sb.append(read).append("\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
        return Objects.isNull(sb) ? null : sb.toString();
    }
}
